import { Component, OnInit } from "@angular/core";
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router } from "@angular/router"; //路由引入
import {config} from '../../../shared/smartadmin.config';

declare var $: any;
@Component({
  selector: "resources-manage",
  templateUrl: "./resources-manage.component.html",
  styleUrls: ["./resources-manage.css"],
})
export class ResourcesManageComponent implements OnInit {
  tableData: any = []; //table数据
  totalCount: number = 0; //分页总条数
  curPage: number = 1; //分页当前页
  pageSize: number = 10; //内置的分页每页条数
  resourceType: any = ''; //资源类型
  searchKey: any = ''; //模糊搜索
  pageType: any = 'new';
  typeList = [{
		value:0,
		label:'菜单'
	},{
		value:1,
		label:'按钮'
	},{
		value:2,
		label:'字段'
	}];
  page: any = {
    type: '',
    sourceKey: '',
    name: '',
		level: 1, //默认顶级
		isHide: 1, //1-开，0-关
		parentName: '',
		parentId: ''
  }
  resourceId = "";
  resourceList: any = [];
  selectMenus = ''; //菜单选中显示值
	isShowAdd: boolean = false;
	isShowDel: boolean = false;
	isShowEdit: boolean = false;


  constructor(private jsonApiService: JsonApiService, private router: Router) {}
  ngOnInit() {
		var that = this;
		this.initBtn();
    System.import('assets/js/bootstrap-switch.min.js').then(
			()=>{System.import('assets/css/bootstrap-switch.min.css').then(()=>{
				this.load();
			})
		});
		System.import('assets/js/jstree/jstree.min.js').then(()=>{
			that.load_company().then(()=>{
				var tree_box = document.getElementById('tree_box');
				var company = document.getElementById('company');
				document.onclick=function(e:any){
					if(!(e.target === company||e.target.className === 'jstree-children'||e.target.className === 's_del_icon'||e.target.className === 'jstree-node  jstree-leaf'||e.target.className === 'jstree-icon jstree-ocl'||e.target.className ==='vision_tree'||e.target.className === 'jstree-node jstree-leaf jstree-closed'||e.target.className == 'treeSearchInput')){ 
						tree_box.className = tree_box.className.replace("tree_open","");
					} 
				}
			})
		})
  }
	//初始化权限按钮
	initBtn() {
		var btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_appletsManage:resourcesManage')));
		if(!btnData) {
			return
		};
		for(let item of btnData) {
			if(item.sourceKey === "resourcesManage:addBtn" && item.parentId) {
				this.isShowAdd = true;
			}
			if(item.sourceKey === "resourcesManage:delBtn" && item.parentId) {
				this.isShowDel = true;
			}
			if(item.sourceKey === "resourcesManage:editBtn" && item.parentId) {
				this.isShowEdit = true;
			}
		}
	}
  //table刷新
  refresh() {
    this.load();
  }
  //初始化加载list数据  TODO
  load() {
		let that = this
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				searchKey: this.searchKey.trim(),
				type: this.resourceType
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(data);
    this.jsonApiService.http("appletResource/list.html", reqdata).subscribe((result) => {
      this.tableData = result.exhibitDatas || [];
      this.totalCount = result.recordCount;

      System.import("assets/js/bootstrap-switch.min.js").then(() => {
        System.import("assets/css/bootstrap-switch.min.css").then(() => {
          setTimeout(function () {
            that.initSwitch();
          }, 1);
        });
      });
    });
  }
  //表格搜索
	table_search() {
		this.curPage = 1;
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1;
    this.pageSize = e.rows;
    this.load();
  }
  //初始化开关
  initSwitch() {
    var that = this;
    $(".isEnable").bootstrapSwitch({
      //初始化按钮
      onText: "开启",
      offText: "停用",
      onColor: "primary",
      offColor: "warning",
      onSwitchChange: function (event, state) {
        if (state == true) {
          that.checkStatus("1", event.target.id);
        } else {
          that.checkStatus("0", event.target.id);
        }
      },
    });
  }
  //是否启用
  checkStatus(check, id) {
		this.page.isHide = check;
		let reqdata = 'id=' +id + '&isHide=' + check;
    this.jsonApiService.http('appletResource/updateStatus.html',reqdata).subscribe((data) => {
      if (data.success) {
        this.load();
      } else {
        this.jsonApiService.message(data.message);
      }
    });
  }
  // 删除
  examineDelete(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			let reqdata = 'ids=' + row.id;
			this.jsonApiService.http("appletResource/deleteBatch.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if(data.success) {
					this.load();
				}
			})
		})
  }

	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			type: {
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择资源类型'
					}
				}
			},
			sourceKey: {
				validators: {
					notEmpty: {
						message: '请输入资源标识'
					}
				}
			},
			name: {
				validators: {
					notEmpty: {
						message: '请输入资源名称'
					},
					stringLength: {
						max: 30,
						message: '资源名称30字以内'
					},
//					remote: {
//			            message: '资源名称已存在',
//			            url: config.BaseURL+"resource/validateResourceName.html",
//			            data: function(validator) {
//                          return {
//                              id: validator.getFieldElements('name').attr("resourceId")
//                          };
//                      },
//		        	}
				}
			},
		}
	}

  //编辑
  editResources(row, modal) {
		modal.show();
    this.pageType = 'updata';
		$('#tree').jstree(true).refresh();
		$("#resourceForm").data('bootstrapValidator').resetForm();
    this.resourceId = row.id;
		this.selectMenus = ''
		for(let item in this.page) {
			if(item == 'type'){
				this.page[item] = row[item];
			}else{
				this.page[item] = row[item]||'';
			}
		}
		this.resourceList.forEach(item=>{
			if(item.id === this.page.parentId){
				this.selectMenus = item.text;
			}
		});					
		
		
  }
  // 添加
  addResources(modal) {
		modal.show();
		this.pageType = 'new';
		this.resourceId = '';
		$("#resourceForm").data('bootstrapValidator').resetForm();
		this.page = {
			type: '',
			sourceKey: '',
			name: '',
			level: 1, //默认顶级
			isHide: 1, //1-开，0-关
			parentName: '',
			parentId: ''
		}
		this.selectMenus = '';
		$('#tree').jstree(true).refresh();
  }

  typeChange(e){
		this.page.type = +e;
		$("#resourceForm").data('bootstrapValidator').resetForm();
	}

  // 提交
  resourcesSubmit(modal) {
    $('#resourceForm').bootstrapValidator('validate'); //开启验证
		var isValid = $('#resourceForm').data('bootstrapValidator').isValid();  //验证是否通过

		if(isValid){
			var reqdata = '';
      for(let item in this.page){
        reqdata += item+'='+this.page[item]+'&';
      }
      reqdata = reqdata.substring(0,reqdata.length-1);
      if(this.pageType === 'new'){
      }else if(this.pageType === 'updata'){
        reqdata = reqdata+'&id='+this.resourceId;
      }
      this.jsonApiService.http('appletResource/modify.html',reqdata).subscribe(data=> {
        this.jsonApiService.message(data.message);
        if(data.success){
					modal.hide();
          this.load();
        }
      })
		}
  }
  //关闭
  resourcesClose(modal) {
		$("#resourceForm").data('bootstrapValidator').resetForm();
    modal.hide();
  }


  //公司树显示隐藏事件
	companyClick(){
		$('#tree_box').toggleClass('tree_open');
	}
	//擦除公司所选值
	delText(){
		$('#company').val("");
		$('#company').val('').change();
		if($('#tree_box')[0].className.indexOf('tree_open')>0){
			$('#company').focus();
		}
	}
	//拉取上级名称树数据
	load_company(){
		var that = this;
		return new Promise(function(resolve,reject){
			$('#tree').jstree({
				"core": {
					'data': function(obj, callback) {       
						var jsonstr = "[]";       
						var jsonarray = eval('(' + jsonstr + ')');
						var url = 'appletResource/listByTree.html';
						$.ajax({        
							type: "post",
							url: config.BaseURL + url,
							dataType: "json",
							xhrFields: {
								withCredentials: true
							},
							success: function(result) {							
								jsonarray = result.data;
								that.resourceList = jsonarray;
								jsonarray.map(item=>{
									if(!item.parent){
										item.parent = '#';
									}else{
										item.parent = item.parent;
									}
									item.level = item.level;
									item.state = {disabled: false, opened: true, selected: false};
								});
								resolve();
								callback.call(this, jsonarray);
							}         
						});    
					},

					"themes": {
						"responsive": true
					},
					"multiple": false,
					"animation": 200,
					"dblclick_toggle": true,
					"expand_selected_onload": true
				},
				"plugins": ["search"]
			}).bind("activate_node.jstree", function(e, obj) {
				var currentNode = obj.node; // 获取当前节点   
				that.page.parentId = currentNode.id;
				that.page.parentName = currentNode.text;
				that.page.level = parseInt(currentNode.original.level)+1;
				$('#company').val(currentNode.text).change();
			})
		})
	}
	//公司树模糊搜索
	companySearch() {
		var that = this;
		var value = $('#tree_box').find('.treeSearchInput').val();
		$('#tree_box').find('#tree').eq(0).jstree(true).search(value);
		let searchResult = $('#tree_box').find('.jstree-search').length;
		if(searchResult < 1) {
			return;
		}
		$('#tree_box').find('.jstree-search').each(function(index, obj) {
			if(index < 1) { //js树搜索定位到结果的第一个地方；
				let container = $('#tree_box').find('.vision_tree');
				let scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({
					scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
				});
			}
		})
	}
	//公司树模糊搜索	click
	companySearchBtn() {
		var that = this;
		var value = $('#tree_box').find('.treeSearchInput').val();
		$('#tree_box').find('#tree').eq(0).jstree(true).search(value);
		let searchResult = $('#tree_box').find('.jstree-search').length;
		if(searchResult < 1) {
			that.jsonApiService.message('未搜索到结果');
			return;
		}
		$('#tree_box').find('.jstree-search').each(function(index, obj) {
			if(index < 1) { //js树搜索定位到结果的第一个地方；
				let container = $('#tree_box').find('.vision_tree');
				let scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({
					scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
				});
			}
		})
	}
}
